package cn.bearspark.comment.provider.dao.buffer;

import cn.bearspark.common.enumeration.ModuleEnum;
import cn.bearspark.comment.enumeration.CommentOrderEnum;
import cn.bearspark.comment.provider.dao.key.BldgCommentBufferKeyBuilder;
import cn.bearspark.comment.provider.dao.mapper.BldgCommentMapper;
import cn.bearspark.common.dto.Page;
import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 楼评论 id 集合的缓存器
 *
 * @author f
 */
@Component
public class BldgCommentIdListBuffer extends RedisBaseListBuffer<Long> {

    /**
     * "最新" 排序方式的枚举值
     */
    private static final int NEWEST_CODE = CommentOrderEnum.NEWEST.getCode();

    /**
     * "最热" 排序方式的枚举值
     */
    private static final int HOTTEST_CODE = CommentOrderEnum.HOTTEST.getCode();

    private final BldgCommentMapper bldgCommentMapper;

    private final BldgCommentBufferKeyBuilder bldgCommentBufferKeyBuilder;

    public BldgCommentIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                                   BldgCommentMapper bldgCommentMapper,
                                   BldgCommentBufferKeyBuilder bldgCommentBufferKeyBuilder) {
        super(redisTemplate);
        this.bldgCommentMapper = bldgCommentMapper;
        this.bldgCommentBufferKeyBuilder = bldgCommentBufferKeyBuilder;
    }

    /**
     * 分页查询动态的楼评论 id
     *
     * @param pageNum     评论的页数
     * @param pageSize    评论的条数
     * @param happeningId 待查询评论的动态 id
     * @param order       评论排序的方式
     * @return 楼评论分页查询的信息
     */
    public Page<Long> pageHappeningBldgId(int pageNum, int pageSize, long happeningId, int order) {
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize - 1;
        String key = bldgCommentBufferKeyBuilder.buildBldgIdInfoKey(happeningId, order);
        Page<Long> idPage = new Page<>();
        idPage.setTotal(bldgCommentMapper.count(happeningId));
        idPage.setRecords(super.range(key, start, end, () -> order == NEWEST_CODE ?
                bldgCommentMapper.listBldgIdOrderByPubTime(start, pageSize, happeningId) :
                bldgCommentMapper.listBldgIdOrderByLikeNum(start, pageSize, happeningId)
        ));
        return idPage;
    }

    /**
     * 清理动态楼评论 id 集合的缓存
     *
     * @param happeningId 待清理缓存的动态 id
     */
    public void cleanHappening(long happeningId) {
        super.clean(
                bldgCommentBufferKeyBuilder.buildBldgIdInfoKey(happeningId, NEWEST_CODE),
                bldgCommentBufferKeyBuilder.buildBldgIdInfoKey(happeningId, HOTTEST_CODE)
        );
    }

}
